package com.itheima.leyou.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.leyou.dao.StockDao;
import com.itheima.leyou.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class StockService {
    /**
     * 秒杀政策redis的key前缀，后面拼上sku_id作为一个完整的key
     */
    private static final String STOCK_LIMIT_POLICY_ = "STOCK_LIMIT_POLICY_";

    /**
     * 引入restTemplate的bean
     */
    @Autowired
    RestTemplate restTemplate;

    /**
     * 引入redis
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private StockDao stockDao;

    public Map<String, Object> getStockList(){
        Map<String, Object> map = new HashMap<>();
        ArrayList<Map<String, Object>> list = null;
        //查询商品列表
        list = stockDao.getStockList();

        if (list==null||list.size()==0){
            map.put("result", false);
            map.put("msg", "未找到相应的商品信息！");
            return map;
        }else {
            //时间服务器当前时间
            String nowTime = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
            //循环判断商品是否存在有效的秒杀政策
            for (Map<String, Object> stockMap : list){
                long sku_id = (Long) stockMap.get("id");
                String limitPolicy = redisTemplate.opsForValue().get(STOCK_LIMIT_POLICY_+sku_id);
                //存在秒杀政策
                if (limitPolicy != null && !"".equals(limitPolicy)){
                    //秒杀政策转为map
                    Map<String, Object> limitPolicyMap = StringUtil.mapStringToMap(limitPolicy);
                    //秒杀开始时间
                    Object beginTime = limitPolicyMap.get("begin_time");
                    //活动开始时间＜当前时间，说明活动已经开始
                    if(StringUtil.getDifferentTime(nowTime,beginTime.toString()) >= 0){
                        //优惠价格
                        stockMap.put("limitPrice", limitPolicyMap.get("price"));
                        //秒杀开始时间
                        stockMap.put("limitBeginTime", limitPolicyMap.get("begin_time"));
                        //秒杀结束时间
                        stockMap.put("limitEndTime", limitPolicyMap.get("end_time"));
                        //秒杀结束时间
                        stockMap.put("nowTime", nowTime);
                    }
                }
            }

            map.put("sku_list", list);
            map.put("result", true);
            map.put("msg", "");
            return map;
        }
    }

    public Map<String, Object> getStock(String sku_id){
        Map<String, Object> map = new HashMap<>();
        if (sku_id==null||sku_id.equals("")){
            map.put("result", false);
            map.put("msg", "获取商品传入的参数为空！");
            return map;
        }
        ArrayList<Map<String, Object>> list = new ArrayList<>();

        list = stockDao.getStock(sku_id);

        if (list==null||list.size()==0){
            map.put("result", false);
            map.put("msg", "通过"+sku_id+"未找到相应的商品信息！");
            return map;
        }

        String limitPolicy = redisTemplate.opsForValue().get("STOCK_LIMIT_POLICY_"+sku_id);
        //时间服务器当前时间
        String nowTime = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
        //循环判断商品是否存在有效的秒杀政策
        for (Map<String,Object> stockMap : list){
            //存在秒杀政策
            if (limitPolicy != null && !"".equals(limitPolicy)){
                //秒杀政策转为map
                Map<String, Object> limitPolicyMap = StringUtil.mapStringToMap(limitPolicy);
                //秒杀开始时间
                Object beginTime = limitPolicyMap.get("begin_time");
                //活动开始时间＜当前时间，说明活动已经开始
                if(StringUtil.getDifferentTime(nowTime,beginTime.toString()) >= 0){
                    //优惠价格
                    stockMap.put("limitPrice", limitPolicyMap.get("price"));
                    //秒杀开始时间
                    stockMap.put("limitBeginTime", limitPolicyMap.get("begin_time"));
                    //秒杀结束时间
                    stockMap.put("limitEndTime", limitPolicyMap.get("end_time"));
                    //秒杀结束时间
                    stockMap.put("nowTime", nowTime);
                }
            }
            map.putAll(stockMap);
        }
        map.put("sku", list);
        map.put("result", true);
        map.put("msg", "");
        return map;
    }

    /**
     * 新增秒杀政策
     * @param jsonObj
     * @return
     */
    @Transactional
    public Map<String, Object> insertLimitPolicy(String jsonObj){
        Map<String, Object> map = JSONObject.parseObject(jsonObj, new TypeReference<Map<String, Object>>(){});

        if (map==null||map.size()==0){
            map.put("result", false);
            map.put("msg", "传入的参数有误，请刷新数据！");
            return map;
        }

        boolean resultFlag = stockDao.insertLimitPolicy(map);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", resultFlag);
        resultMap.put("msg", resultFlag?"新增成功！":"新增失败！");
        //存入redis
        if(resultFlag){
            //时间服务器当前时间
            String nowTime = restTemplate.getForObject("http://leyou-time-server/getTime", String.class);
            long dayTime = StringUtil.getDifferentTime(map.get("end_time").toString(),nowTime);
            redisTemplate.opsForValue().set(STOCK_LIMIT_POLICY_+map.get("sku_id"),map.toString(),dayTime,TimeUnit.SECONDS);
        }
        return resultMap;
    }
}
